<?php
class Agitum_Sms_Gate_Smsc extends Agitum_Sms_Gate_Abstract
{
	public function send($opt = array()) 
	{
		$phones 	= implode(',', $this->param($opt, 'phones', array()));
		$translit 	= $this->param($opt, 'translit', 0);
		$time 		= $this->param($opt, 'time', 0);
		$id 		= $this->param($opt, 'id', 0);
		$flash 		= $this->param($opt, 'flash', 0);
		$sender 	= $this->param($opt, 'sender', $this->_sender);
		$charset 	= $this->param($opt, 'charset', 'utf-8');
		
		$message 	= $this->param($opt, 'message', null);
		if ( $message == null ) {
			throw new Exception('Empty sms message');
		}
		
		$result = $this->_smsc_send_cmd("send", "phones=".urlencode($phones)."&mes=".urlencode($message).
					"&translit=$translit&time=$time&id=$id&flash=$flash&sender=".urlencode($sender)."&charset=$charset");

		if (preg_match("/^OK - (\d+) SMS, ID - (\d+)/", $result, $m)) {
			if ($this->_debug)
				echo "Сообщение отправлено успешно. Всего отправлено SMS: $m[1]. ID сообщения - $m[2]\n";
	
			return $m[2];
		}
		elseif (preg_match("/^ERROR = (\d)(.*?)(?:, ID - (\d+))?$/", $result, $m))
		{
			if ($this->_debug)
				echo "Ошибка № $m[1]$m[2]", isset($m[3]) ? ", ID: ".$m[3] : "", "\n";
	
			return -$m[1];
		}
	
		if ($this->_debug)
			echo "Сервер вернул нераспознанный ответ - ", $result, "\n";
	
		return false;
	}
	
    public function cost($opt = array()) {
		$phones 	= implode(',', $this->param($opt, 'phones', array()));
		$vars 		= $this->param($opt, 'template_vars', array());
		$translit 	= $this->param($opt, 'translit', 0);
		$sender 	= $this->param($opt, 'sender', $this->_sender);
		
		$message = $this->getMessage($vars);
		
		$result = $this->_smsc_send_cmd("send", "phones=".urlencode($phones)."&mes=".urlencode($message)."&sender=".urlencode($sender)."&translit=$translit&cost=1");
	
		if (preg_match("/^([\d\.]+) \((\d+) SMS\)/", $result, $m))
		{
			if ($this->_debug)
				echo "Стоимость рассылки: $m[1] руб. Всего SMS: $m[2]\n";
	
			return $m[1];
		}
		elseif (preg_match("/^ERROR = (\d)(.*?)(?:, ID - (\d+))?$/", $result, $m))
		{
			if ($this->_debug)
				echo "Ошибка № $m[1]$m[2]", isset($m[3]) ? ", ID: ".$m[3] : "", "\n";
	
			return -$m[1];
		}
	
		if ($this->_debug)
			echo "Сервер вернул нераспознанный ответ - ", $result, "\n";
	
		return false;
	}

    public function status($opt = array()) 
    {
    	$id 	= $this->param($opt, 'id', 0);
    	$phone 	= $this->param($opt, 'phone', '');
    	
		$result = $this->_smsc_send_cmd("status", "phone=$phone&id=$id");
	
		if (preg_match("/^Status = (-?\d+)(?:, check_time = (.+))?$/", $result, $m))
		{
			if ($this->_debug)
				echo "Статус SMS = $m[1]", isset($m[2]) ? ", время изменения статуса - $m[2]" : "", "\n";
	
			return $m[1];
		}
		elseif (preg_match("/^ERROR = (\d)(.*)$/", $result, $m))
		{
			if ($this->_debug)
				echo "Ошибка № $m[1]$m[2]\n";
	
			return false;
		}
	
		if ($this->_debug)
			echo "Сервер вернул нераспознанный ответ - ", $result, "\n";
	
		return false;
	}

    public function balance() {
		$result = $this->_smsc_send_cmd("balance");
	
		if (is_numeric($result))
		{
			if ($this->_debug)
				echo "Сумма на счете: ", $result, "\n";
	
			return $result;
		}
		elseif (preg_match("/^ERROR = (\d)(.*)$/", $result, $m))
		{
			if ($this->_debug)
				echo "Ошибка № $m[1]$m[2]\n";
	
			return false;
		}
	
		if ($this->_debug)
			echo "Сервер вернул нераспознанный ответ - ", $result, "\n";
	
		return false;
	}
	
	private function _smsc_send_cmd($cmd, $arg = "") {
		$url = "http://smsc.ru/sys/$cmd.php?login=".urlencode($this->_login)."&psw=".urlencode($this->_pass)."&".$arg;
	
		$i = 0;
		do {
			if ($i)
				sleep(2);
	
			$ret = $this->_smsc_read_url($url);
		}
		while ($ret == "" && ++$i < 3);
	
		return $ret;
	}

	private function _smsc_read_url($url) {
		$ret = "";
	
		if (function_exists("curl_init"))
		{
			$c = curl_init($url);
	
			curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 10);
			curl_setopt($c, CURLOPT_TIMEOUT, 10);
	
			$ret = curl_exec($c);
			curl_close($c);
		}
		elseif (function_exists("fsockopen"))
		{
			$m = parse_url($url);
	
			$fp = fsockopen($m["host"], 80, $errno, $errstr, 10);
	
			if ($fp) {
				fwrite($fp, "GET $m[path]?$m[query] HTTP/1.1\r\nHost: smsc.ru\r\nUser-Agent: CSMSGate\r\nConnection: Close\r\n\r\n");
	
				while (!feof($fp))
					$ret = fgets($fp, 100);
	
				fclose($fp);
			}
		}
		else
			$ret = file_get_contents($url);
	
		return $ret;
	}
}